<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 试卷列表 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-button type="primary" class="handle-del mr10" @click="addDialog">新增试卷</el-button>
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除
                </el-button>
                <el-input v-model="query.keyword" placeholder="输入试卷名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column label="试卷封面" width="100">
                    <template slot-scope="scope">
                        <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id,'tableData')" alt="" class="info-image" />
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="试卷名称"></el-table-column>
                <el-table-column prop="description" label="试卷描述"></el-table-column>
                <el-table-column label="免费/付费">
                    <template slot-scope="scope">
                        <span style="color: #e65c5c">{{ scope.row.price == 0 ? '免费' : '¥ ' +
                        ((scope.row.price)/100).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="f_view" label="浏览量"></el-table-column>
                <el-table-column prop="f_sales" label="订阅量"></el-table-column>
                <el-table-column prop="f_favorites" label="收藏量"></el-table-column>
                <el-table-column label="操作" width="400" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button @click="preview(scope.row.id, scope.row.title)" type="primary" size="mini">预览</el-button>
                        <el-button @click="openColumnManage(scope.row.id, scope.row.title)" type="primary" size="mini">试题管理</el-button>
                        <el-button @click="edit(scope.row.id, scope.row)" type="success" size="mini">编辑</el-button>
                        <el-button @click="putOn(scope.row.id, scope.row.status)" type="warning" size="mini">{{ scope.row.status == 0 ? '上架' : '下架' }}</el-button>
                        <el-button @click="deleteRow(scope.row.id, scope.$index)" type="danger" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.page"
                    :page-size="query.rows" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>
        <!-- 新增试卷弹出框 -->
        <el-dialog title="新增/编辑试卷" @close="cancel" :visible.sync="showDialog" width="50%">
            <el-form ref="form" :rules="rules" :model="form" label-width="100px">
                <el-form-item label="试卷名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="试卷描述" prop="description">
                    <el-input type="textarea" :rows="2" v-model="form.description"> </el-input>
                </el-form-item>
                <el-form-item label="试卷封面">
                    <div class="avatar-uploader" @click="showUploadImage()">
						<img v-if="form.cover" :src="form.cover" class="avatar" height="200px">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</div>
					<div class="el-upload__tip">封面建议尺寸：800*600px，支持jpg、png</div>
                </el-form-item>
                <el-form-item label="分类" prop="category_id">
                    <el-select v-model="form.category_id" clearable placeholder="请选择课程分类">
                        <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                        <el-option-group v-for="group in options" :key="group.index">
                            <el-option v-for="item in group._child" :key="item.id" :label="item.title" :value="item.id">
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="试卷总分">
                    <el-input v-model="form.total"></el-input>
                </el-form-item>
                <el-form-item label="及格分数">
                    <el-input v-model="form.pass"></el-input>
                </el-form-item>
                <el-form-item label="作答时间">
                    <el-input v-model="form.exam_time" placeholder="单位：分钟"></el-input>
                </el-form-item>
                <el-form-item label="会员专享">
                    <el-checkbox :true-label="1" :false-label="0" v-model="form.only_member">勾选后仅会员可订阅</el-checkbox>
                </el-form-item>
                <el-form-item label="支持答题模式">
                    <el-checkbox :true-label="1" :false-label="0" v-model="form.exam_support">考试</el-checkbox>
                    <el-checkbox :true-label="1" :false-label="0" v-model="form.test_support">模拟练习</el-checkbox>
                </el-form-item>
                <el-form-item label="是否付费">
                    <el-radio-group v-model="form.expense">
                        <el-radio :label="0">免费</el-radio>
                        <el-radio :label="1">付费</el-radio>
                    </el-radio-group>
                    <div v-if="form.expense == 1">
                        <el-form-item label="商品价格">
                            <el-input v-model="form.price" class="showPay"></el-input><span>元</span>
                        </el-form-item>
                        <el-form-item label="划线价格">
                            <el-input v-model="form.marking_price" class="showPay"></el-input><span>元</span>
                        </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item label="返还积分">
                    <el-input v-model="form.score"></el-input>
                </el-form-item>
                <el-form-item label="选择讲师" prop="teacher_id">
					<el-button @click="chooseLecturer" type="primary" size="mini">选择讲师</el-button>
					<el-table :data="selectRowData" v-if="selectRowData.length !== 0" class="table" ref="multipleTable"
						header-cell-class-name="table-header">
						<el-table-column label="讲师图片">
							<template slot-scope="scope">
								<img :src="scope.row.cover" alt="" class="info-image" />
							</template>
						</el-table-column>
						<el-table-column prop="name" label="讲师姓名"></el-table-column>
						<el-table-column prop="description" label="讲师描述"></el-table-column>
						<el-table-column label="操作" align="center">
							<el-button @click="del_lecturer" type="danger" size="mini">移除讲师</el-button>
						</el-table-column>
					</el-table>
				</el-form-item>
                <el-form-item label="自定义浏览量">
                    <el-input v-model="form.f_view"></el-input>
                </el-form-item>
                <el-form-item label="自定义订阅量">
                    <el-input v-model="form.f_sales"></el-input>
                </el-form-item>
                <el-form-item label="自定义收藏量">
                    <el-input v-model="form.f_favorites"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item label="状态设置">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">立即上架</el-radio>
                        <el-radio :label="0">暂不上架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save('form')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 预览弹出框 -->
        <el-dialog :title="title" :visible.sync="previewDialogVisible" width="30%">
            <div class="preview">
                <h3>微信扫码预览</h3>
                <qriously class="qrCode" :value="preview_url" :size="200" :backgroundAlpha="1" />
                <el-input v-model="preview_url">
                    <template slot="prepend">SPA版url</template>
                    <el-button v-clipboard="copy_value" v-clipboard:success="clipboardSuccessHandler"
                        v-clipboard:error="clipboardErrorHandler" slot="append">复制</el-button>
                </el-input>
            </div>
        </el-dialog>
        <!-- 讲师弹框 -->
		<el-dialog width="36%" title="选择讲师" @close="exit" :visible.sync="innerVisible" append-to-body>
			<el-form ref="form" :model="form" label-width="100px">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="输入讲师姓名" class="handle-input mr10"></el-input>
					<el-button type="primary" icon="el-icon-search" @click="lecturerSearch">搜索</el-button>
				</el-form-item>
				<el-table :data="chooseLecturerTableData" @row-click="chooseRow" class="chooseLecturerTable"
					ref="multipleTable" header-cell-class-name="table-header">
					<el-table-column prop="name" label="讲师图片">
						<template slot-scope="scope">
							<img :src="scope.row.cover" alt="" class="info-image" />
						</template>
					</el-table-column>
					<el-table-column prop="name" label="讲师姓名"></el-table-column>
					<el-table-column prop="description" label="讲师描述"></el-table-column>
				</el-table>
				<div class="pagination">
					<el-pagination background layout="total, prev, pager, next" :current-page="query.page"
						:page-size="query.rows" :total="lecturerListTotal" @current-change="lecturerPageChange">
					</el-pagination>
				</div>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="exit">关 闭</el-button>
			</span>
		</el-dialog>
        <uploadimage ref="uploadimagecom" v-on:childByImageValue="childByImageValue"></uploadimage>
    </div>
</template>

<script>
import { examListData, classifyListData, addExamData, delExamData,lecturerListData } from '../../api/index';
import uploadimage from '@/components/common/uploadimage.vue';
export default {
    components: {
		uploadimage
	},
    // name: 'lecturer',
    data() {
        return {
            query: {
                page: 1,
                rows: 4,
                keyword: ''
            },
            imgUrl: 'http://api.xuejing.pro/admin/file/image',
            pictureList: [],
            title: '',
            preview_url: '',
            copy_value: '',
            form: {
                id: '',
                title: '',
                description: '',
                cover: '',
                category_id: '',
                total: '',
                pass: '',
                exam_time: '',
                only_member: '',
                exam_support: '',
                test_support: '',
                expense: '',
                price: '',
                marking_price: '',
                score: '',
                f_view: '',
                f_sales: '',
                f_favorites: '',
                sort: '',
                status: 1
            },
            rules: {
                title: [
                    { required: true, message: "请输入试卷名称", trigger: "blur" },
                    { min: 1, max: 30, message: "请输入1到30位的字符", trigger: "blur" }
                ],
                teacher_id: [{ required: true, message: "请选择讲师", trigger: "bulr" }],
                category_id: [{ required: true, message: "请选择分类", trigger: "blur" }]
            },
            options: [],
            // options_child: [],
            tableData: [],
            multipleSelection: [],
            delList: [],
            showDialog: false,
            previewDialogVisible: false,
            pageTotal: 0,
            chooseLecturerTableData: [],
            selectRowData: [],
            innerVisible:false,
            lecturerListTotal: 0,
            errorProduct: require('@/assets/img/noProduct.jpg'), 
        };
    },
    created() {
        this.getData();
    },
    methods: {
        tabErrorPicture(id,data){    // 表格图文封面默认展示图
            let i = this[data].findIndex(v => v.id == id);
			this[data][i].cover = this.errorProduct;
        },
        getData() {
            examListData(this.query).then((res) => {
                this.tableData = res.data.list;
                this.pageTotal = res.data.count;
            });
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //批量删除
        delAllSelection() {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const length = this.multipleSelection.length;
                let str = '';
                let strID = '';
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].title + ' ';
                    strID += this.multipleSelection[i].id + ',';
                }
                delExamData({ id: strID.substring(0, strID.lastIndexOf(',')) }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success(`删除了${str}`);
                        this.multipleSelection = [];
                        this.getData();
                    }
                });
            });
        },
        // 搜索
        handleSearch() {
            this.$set(this.query);
            this.getData();
        },
        // 封面上传
        handleCover(res) {
            if (res.code == 1) {
                this.form.cover = res.data.attachment;
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.form.dialogVisible = true;
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
        },
        //新增
        addDialog() {
            this.showDialog = true;
            classifyListData().then((res) => {
                this.options = res.data.list;
                // res.data.list.forEach((item) => {
                //     if (item._child) {
                //         console.log(item);
                //         this.options_child.push(item);
                //         console.log(this.options_child);
                //     }
                // });
            });
        },
        // 预览
        preview(id, title) {
			let shop_domainname=localStorage.getItem('domainname');
			
            this.previewDialogVisible = true;
            this.title = title;
            this.copy_value =
                // this.preview_url = `http://www.nashicike.top/addons/muu_classroom/h5/?i=1#/muu_classroom/pages/exam/paper/detail?id=${id}`; 
				this.preview_url = `http://www.nashicike.top/xuejing/exampreview/${shop_domainname}?id=${id}&domainname=${shop_domainname}`;
        },
        clipboardSuccessHandler({ value, event }) {
            this.$message.success('复制成功');
        },
        clipboardErrorHandler({ value, event }) {
            console.log('复制失败', value);
        },
        openColumnManage(id, title) {
            this.$router.push({ path: '/aidTool/examManage', query: { id, title } });
        },
        //编辑
        edit(id, row) {
            classifyListData().then((res) => {
                this.options = res.data.list;
            });

            this.showDialog = true;
            this.form = row;
            this.form.id = id;
            if (row.cover) {
                this.pictureList.push({
                    url: row.cover
                });
            }
        },
        //上下架
        putOn(id, status) {
            this.$confirm(`确定${status == 0 ? '上架' : '下架'}吗！`, '提示', {
                type: 'warning'
            }).then(() => {
                addExamData({ id: id, status: status == 0 ? 1 : 0 }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('成功');
                        this.getData();
                        //location.reload();
                    }
                });
            });
        },
        //删除
        deleteRow(id, index) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                delExamData({ id: id }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                        this.getData();
                    }
                });
            });
        },
        //取消
        cancel() {
            this.pictureList = [];
            this.showDialog = false;
            // location.reload();
        },
        //确定
        save(formName) {
            // let formData = new FormData();
            // formData.append('cover', this.cover);
            // formData.append('column', this.column);
            // formData.append("form", JSON.stringify(this.form));
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    addExamData(this.form).then((res) => {
                        if (res.code == 1) {
                            this.showDialog = false;
                            this.getData();
                            //location.reload();
                        }
                    });
                }else{
                    return false
                }
            })

        },
        // 分页
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        chooseLecturer() {
			this.innerVisible = true;
			lecturerListData(this.query).then((res) => {
				this.chooseLecturerTableData = res.data.list;
				this.lecturerListTotal = res.data.count;
			});
		},
        chooseRow(row) {
			this.selectRowData = [];
			this.selectRowData.push(row);
			this.form.teacher_id = row.id;
			this.innerVisible = false;
		},
		//关闭
		exit() {
			this.innerVisible = false;
		},
        // 讲师搜索
		lecturerSearch() {
			this.chooseLecturer();
		},
		// 讲师分页
		lecturerPageChange(val) {
			this.$set(this.query, 'page', val);
			this.chooseLecturer();
		},
		del_lecturer() {
			this.selectRowData = [];
			this.form.teacher_id = '';
		},
        showUploadImage() { //显示上传组件
			this.$refs.uploadimagecom.dialogVisible = true;
		},
        //确认按钮传值过来并赋值到form表单上
		childByImageValue: function (childValue) {
				this.form.cover = childValue;
		}
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    float: right;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.mr10 {
    margin-right: 10px;
}

.info-image {
    width: 80px;
    border-radius: 4px;
}

.showPay {
    width: 150px;
    margin-right: 10px;
    margin-bottom: 15px;
}

.preview {
    padding: 30px;
    text-align: center;
}

.preview .qrCode {
    margin: 10px 0;
}
</style>

<style>
.el-upload--text {
    border: 0;
    height: 40px;
    text-align: left;
    overflow: unset;
}

.el-upload__tip {
    margin-top: 0;
}

.el-input-group__append {
    background: #e6a23c;
}

.el-input-group__append span {
    color: #fff;
}

.avatar-uploader {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	width: 375px !important;
	text-align: center;
}

.avatar-uploader:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
}

.avatar {
	width: 100%;
	display: block;
}
</style>


